package fetcher

import (
	"bytes"
	"igxe-change/model"
	"io/ioutil"
	"net/http"
	"time"
)

type Fetcher struct {
	User *model.User
}

var rateLimiter = time.Tick(time.Second)

func (fetcher *Fetcher) Get(url string) ([]byte, error) {
	req, err := http.NewRequest(http.MethodGet, url, bytes.NewBufferString(""))

	if err != nil {
		return nil, err
	}

	return fetcher.doRequest(req)
}

func (fetcher *Fetcher) Post(url string, body []byte) ([]byte, error) {
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(body))

	if err != nil {
		return nil, err
	}

	return fetcher.doRequest(req)
}

func (fetcher *Fetcher) Put(url string, body []byte) ([]byte, error) {
	req, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(body))

	if err != nil {
		return nil, err
	}

	return fetcher.doRequest(req)
}

func (fetcher *Fetcher) doRequest(req *http.Request) ([]byte, error) {
	<-rateLimiter
	fetcher.setRequestHeaders(req)

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return nil, err
	}

	return content, nil
}

func (fetcher *Fetcher) setRequestHeaders(r *http.Request) {
	r.Header.Set("token", fetcher.User.Token)
	r.Header.Set("Content-Type", "application/json")
	r.Header.Set("Host", "www.igxe.cn")
	r.Header.Set("User-Agent", "IGXEAssistant/1.0.0 (iPhone; iOS 12.0; Scale/3.00)")
}
